package com.phenix.tools.coder;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;


/**
 * MD5工具类
 * @author zhenghui
 * @date 2019-10-24
 */
public class MD5Utils {

    private static final int HEX_VALUE_COUNT = 16;

    private static final String DEFAULT_CHARTSET = "UTF-8";

    public static String getMD5(byte[] bytes) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] str = new char[16 * 2];
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] tmp = md.digest();
            int k = 0;
            for (int i = 0; i < HEX_VALUE_COUNT; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(str);
    }

    public static String getMD5(String value) {
        String result = "";
        try {
            result = getMD5(value.getBytes(DEFAULT_CHARTSET));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String getMD5(String value, String encode) {
        String result = "";
        try {
            result = getMD5(value.getBytes(encode));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 判断用户密码是否正确
     *
     * @param newPassword 用户输入的密码
     * @param oldPassword 数据库中存储的密码－－用户密码的摘要
     * @return
     */
    public static Boolean checkPassword(String newPassword, String oldPassword) {
        if(StringUtils.isBlank(newPassword)){
            return false;
        }
        if (getMD5(newPassword, DEFAULT_CHARTSET).equals(oldPassword)) {
            return true;
        }
        return false;
    }
}